package com.mengchengnet.chaperonage.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.mengchengnet.chaperonage.BaseActivity;
import com.mengchengnet.chaperonage.BaseFragment;
import com.mengchengnet.chaperonage.R;
import com.mengchengnet.chaperonage.domain.base.City;
import com.mengchengnet.chaperonage.ui.activity.CareListActivity;
import com.mengchengnet.chaperonage.ui.activity.ChooseCityActivity;
import com.mengchengnet.chaperonage.ui.activity.MainActivity;
import com.mengchengnet.chaperonage.util.PreferenceUtil;
import com.mengchengnet.chaperonage.util.Url;
import com.mengchengnet.chaperonage.util.ViewUtil;
import com.mengchengnet.chaperonage.view.ImageCycleView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.nostra13.universalimageloader.core.ImageLoader.TAG;

/**
 * Created by Administrator on 15-12-24.
 */
public class HomeFragment extends BaseFragment implements View.OnClickListener {

    private View view;
    private View.OnClickListener chooseCityListener;
    private ImageCycleView mImageCycleView;
    private City city;
    private LinearLayout iv_hugong,iv_yuesao,iv_yuying,iv_cuiru;
    private RequestQueue requestQueue;
    //轮播图信息列表
    private List<ImageCycleView.ImageInfo> list = new ArrayList<>();
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mImageCycleView.loadData(list, new ImageCycleView.LoadImageCallBack() {
                @Override
                public ImageView loadAndDisplay(ImageCycleView.ImageInfo imageInfo) {
                    ImageView imageView = new ImageView(BaseActivity.currentActivity);
                    ViewUtil.showImageView(BaseActivity.currentActivity, imageView, imageInfo.image.toString());
                    return imageView;
                }
            });
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_home, null);
        }
        requestQueue= Volley.newRequestQueue(getContext());
        getBanner();
        iv_hugong= (LinearLayout) view.findViewById(R.id.frg_home_pic1);
        iv_yuesao= (LinearLayout) view.findViewById(R.id.frg_home_pic2);
        iv_yuying= (LinearLayout) view.findViewById(R.id.frg_home_pic3);
        iv_cuiru= (LinearLayout) view.findViewById(R.id.frg_home_pic4);
        iv_hugong.setOnClickListener(this);
        iv_yuesao.setOnClickListener(this);
        iv_yuying.setOnClickListener(this);
        iv_cuiru.setOnClickListener(this);

        mImageCycleView = (ImageCycleView) view.findViewById(R.id.icv_topView);

        mImageCycleView.setIndicationStyle(ImageCycleView.IndicationStyle.COLOR, Color.WHITE, getResources().getColor(R.color.colorPrimary), 0.5f);
//        mImageCycleView.setOnPageClickListener(new ImageCycleView.OnPageClickListener() {
//            @Override
//            public void onClick(View imageView, ImageCycleView.ImageInfo imageInfo) {
//                if (imageInfo.flag.equals("1")) {
//                    Toast.makeText(getContext(), "点击了第二张图片", Toast.LENGTH_SHORT).show();
//                }else if(imageInfo.flag.equals("0")){
//                    Toast.makeText(getContext(), "点击了第一张图片", Toast.LENGTH_SHORT).show();
//                }
//                else if(imageInfo.flag.equals("2")){
//                    Toast.makeText(getContext(), "点击了第三张图片", Toast.LENGTH_SHORT).show();
//                }
//            }
//        });


//        list.add(new ImageCycleView.ImageInfo("http://pic76.nipic.com/file/20150826/12702443_165135194000_2.jpg", "", "0", ""));
//        list.add(new ImageCycleView.ImageInfo("http://pic.58pic.com/58pic/12/81/91/94858PICWxT.jpg", "", "1", "https://www.baidu.com"));
//        list.add(new ImageCycleView.ImageInfo("http://pic39.nipic.com/20140312/18085061_092729513131_2.jpg", "", "2", ""));



        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null)

        {
            parent.removeView(view);
        }

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        MainActivity.toolbarState = MainActivity.TOOLBAR_STYLE_HOME;
        mainActivity.initToolbar("梦城陪护");
        chooseCityListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), ChooseCityActivity.class);
                startActivityForResult(intent, 1);
                getActivity().overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
            }
        };
        mainActivity.setChooseCityListener(chooseCityListener);
        //city = CitySvc.getSelectedCity();
        //Log.e(TAG, "城市：");
        //PreferenceUtil.putString(getContext(),"cityName",city.getCityName());
        //PreferenceUtil.putString(getContext(),"cityId",city.getCityId());
        //mainActivity.setCity(city.getCityName());
        //getBanner();
//        mImageCycleView.loadData(list, new ImageCycleView.LoadImageCallBack() {
//            @Override
//            public ImageView loadAndDisplay(ImageCycleView.ImageInfo imageInfo) {
//                ImageView imageView = new ImageView(BaseActivity.currentActivity);
//                ViewUtil.showImageView(BaseActivity.currentActivity, imageView, imageInfo.image.toString());
//                return imageView;
//            }
//        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.frg_home_pic1:
                Intent intent =new Intent();
                intent.putExtra("name","陪护师");
                intent.setClass(getActivity(),CareListActivity.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                break;
            case R.id.frg_home_pic2:
                Intent intent2 =new Intent();
                intent2.putExtra("name","月嫂");
                intent2.setClass(getActivity(),CareListActivity.class);
                startActivity(intent2);
                getActivity().overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                break;
            case R.id.frg_home_pic3:
                Intent intent3 =new Intent();
                intent3.putExtra("name","育婴师");
                intent3.setClass(getActivity(),CareListActivity.class);
                startActivity(intent3);
                getActivity().overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                break;
            case R.id.frg_home_pic4:
                Intent intent4 =new Intent();
                intent4.putExtra("name","催乳师");
                intent4.setClass(getActivity(),CareListActivity.class);
                startActivity(intent4);
                getActivity().overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                break;

            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == mainActivity.RESULT_OK) {
                    Log.e(TAG, "onActivityResult: "+data.getStringExtra("SelectedCity"));
                    mainActivity.setCity(data.getStringExtra("SelectedCity"));
                }
                break;
            default:
        }
    }


    private void getBanner(){
        StringRequest request = new StringRequest(Request.Method.POST, Url.getBanner,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        Log.e("rrrrrrrrr", "获取广告banner返回值："+result );
                        JSONObject jsonObject;
                        try {
                            if(result != null && result.startsWith("\ufeff"))
                            {
                                result =  result.substring(1);
                            }
                            jsonObject = new JSONObject(result);
                            if (jsonObject.getString("code").equals("00")){
                                JSONArray array=jsonObject.getJSONArray("adList");
                                for (int i = 0; i < array.length(); i++) {
                                    JSONObject obj=array.getJSONObject(i);
                                    String imageUrl=obj.getString("imageUrl");
                                    if(list.size()<array.length()){
                                        list.add(new ImageCycleView.ImageInfo(imageUrl, "", String.valueOf(i), ""));
                                    }

                                }

                                    handler.sendEmptyMessage(0);
                            }
                            else {

                                Toast.makeText(getContext(),"defeat",Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                Toast.makeText(getContext(), "网络异常,请稍后重试！", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("version", PreferenceUtil.getString(getContext(),"versionCode"));
                map.put("city_id", "22");//// TODO: 2017/9/18 城市id
                return map;
            }
        };
        request.setTag("GetFenZu");
        request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, // 默认超时时间，应设置一个稍微大点儿的
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, // 默认最大尝试次数
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(request);

    }
}
